package org.kernely.mail;

import java.io.IOException;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.kernely.mail.service.KernelyMailPreparation;
import org.kernely.mail.service.KernelyMailService;
import org.kernely.security.persistence.UserDetails;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;

public class KernelyMailServiceImpl implements KernelyMailService {

	private static JavaMailSender mailSender;

	private static VelocityEngineFactoryBean velocityEngineBean;

	private static VelocityEngine velocityEngine;

	/**
	 * Sets the mail sender.
	 * @param mailSenderExt The mail sender.
	 */
	public void setMailSender(JavaMailSender mailSenderExt)
	{
		mailSender = mailSenderExt;
	}

	/**
	 * Sets the velocity engine.
	 * @param velocityEngine The velocity engine.
	 */
	public void setVelocityEngine(VelocityEngineFactoryBean velocityEngine) {
		velocityEngineBean = velocityEngine;
		this.setVelocityEngine();
	}

	private void setVelocityEngine(){
		try {
			velocityEngine = velocityEngineBean.createVelocityEngine();
		} catch (VelocityException e) {
			// TODO Set a logger
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Set a logger
			e.printStackTrace();
		}
	}

	/**
	 * @see org.kernely.mail.service.KernelyMailService#sendMail(KernelyMailPreparation, java.lang.String[])
	 */
	public void sendMail(final KernelyMailPreparation mailPreparation, final String ... recipients) {
		MimeMessagePreparator emailPrep = new MimeMessagePreparator() {

			public void prepare(MimeMessage mimeMsg) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMsg);
				message.setTo(recipients);
				message.setFrom("kernely-noreply@prometil.com");
				message.setSubject(mailPreparation.getSubject());
				//				 String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, infos.get("template"), infos);
				//				 message.setText(text, true);
				message.setText(mailPreparation.getText(), true);
			}
		};
		mailSender.send(emailPrep);
	}

	/**
	 * @see org.kernely.mail.service.KernelyMailService#sendMailToUser(KernelyMailPreparation, org.kernely.security.persistence.UserDetails[])
	 */
	public void sendMailToUser(KernelyMailPreparation mail, UserDetails ... recipients) {
        String[] recipientsString = new String[100];
        int i = 0;
        for(UserDetails ud : recipients){
                recipientsString[i++] = ud.getMail();
        }
        sendMail(mail, recipientsString);
	}
}
